package com.luoran.system.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.luoran.system.domain.SysPost;
import com.luoran.system.service.ISysPostService;

import java.util.List;

public class PostDataListener implements ReadListener<SysPost> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    private List<SysPost> postList= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ISysPostService postService;

    public PostDataListener(ISysPostService postService){
        this.postService=postService;
    }


    @Override
    public void invoke(SysPost sysPost, AnalysisContext analysisContext) {
        postList.add(sysPost);
        if (postList.size()>=BATCH_COUNT){
            saveData();
            postList=ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }


    public void saveData(){
        postService.saveList(postList);
    }
}
